package com.luotao.test.trade;

import com.luotao.devp.base.service.BaseService;
import com.luotao.devp.base.utils.ConstantsBase;
import com.luotao.devp.base.utils.DateUtils;
import com.luotao.devp.base.utils.MD5Util;
import com.luotao.test.model.User;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * User: luotao
 * Date: 12-5-19
 * Time: 22:07
 */

@Service
public class TradeService extends BaseService {

    private boolean partition = false;

    public void setPartition(boolean partition) {
        this.partition = partition;
    }

    public void trade(Request request) {
        String flowid = UUID.randomUUID().toString();
        Map balc = findUserBalc(request.getCustomerCode());
        Integer balcCharge = (Integer) balc.get("balcCharge");
        Integer balcAward = (Integer) balc.get("balcAward");
        Integer balcLot = (Integer) balc.get("balcLot");
        Date current = new Date();
        String sql_flow_insert = Flow.SQL_INSERT, sql_user_update = User.SQL_UPDATE_BALC;
        if (partition) {
            if (request.getCustomerCode() % 2 != 0) {
                sql_flow_insert = Flow.SQL_INSERT3;
                sql_user_update = User.SQL_UPDATE_BALC3;
            } else {
                sql_flow_insert = Flow.SQL_INSERT4;
                sql_user_update = User.SQL_UPDATE_BALC4;
            }
        }

        update(sql_flow_insert
                , request.getCustomerCode()
                , request.getTradeMoney()
                , balcCharge
                , balcCharge + request.getTradeMoney()
                , 0
                , balcAward
                , balcAward
                , 0
                , balcLot
                , balcLot
                , 1
                , current
                , ConstantsBase.STR_SPACE
                , MD5Util.MD5Encode("tradeMemo")
                , request.getGameCode()
                , 1000
                , 1
                , "iphone"
                , "ticketcode"
                , "ticketcontent"
                , 10
                , 0
                , 10010
                , MD5Util.MD5Encode("ticketMemo")
                , DateUtils.strNow8()
                , DateUtils.strNow8()
        );
        update(sql_user_update, balcCharge - request.getTradeMoney(), balcAward, balcLot, request.getCustomerCode());
    }

    public Map findUserBalc(int userid) {
        String sql = User.SQL_QUERY_BACL;
        if (partition) {
            if (userid % 2 != 0) {
                sql = User.SQL_QUERY_BACL3;
            } else {
                sql = User.SQL_QUERY_BACL4;
            }
        }

        List users = queryForList(sql, userid);
        if (users.size() == 0) {
            throw new RuntimeException("");
        }
        return (Map) users.get(0);
    }
}
